var express = require('express');
var router = express.Router();

router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
    else  next();
});

var DB=require('../../model/db');
var ObjectID=DB.ObjectID;
var sd = require('silly-datetime');
var async = require('async');
var md5 = require("md5-node");
var bodyParser = require('body-parser');

//post数据
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false }));

//登录接口
router.post('/login',function(req,res){
    var tel=req.body.tel;
    var password=md5(req.body.password);
    var msg='';
    var success=0;
    DB.find('user',{
        tel:tel,
        password:password
    },function(err,data){
        if(err) {
            console.log(err);
            return;
        }
        if (data.length > 0) {
            msg:"登录成功",
                success = 1
        }
        else {
            msg:'请检查用户名和密码是否正确',
                success = 0
        }
        res.json({
            result: data,
            msg: msg,
            success: success
        })
    })
})

//判断手机号是否已经注测
router.post('/registerTel',function(req,res){
    var tel=req.body.tel;
    var msg='';
    var success=0;
    DB.find('user',{tel:tel},function(err,data){
        if(err){
            console.log(err);
            return;
        }
        if(data.length>0){


            res.json({
                mes:'用户已注册过请直接登录',
                success:0
            })

        }else{
            res.json({
                mes:'',
                success:1
            })

        }

    })

})

//注册接口 ；
router.post('/register',function(req,res){
    var tel=req.body.tel;
    var password=md5(req.body.password);
    var username = Math.random().toString(35).substr(2).substring(0,9);
    console.log(tel);
    console.log(req.body.password);
    var msg='';
    var success=0;
    DB.insertOne('user',{
        tel:tel,
        password:password,
        username:username
    },function(err,result){
        if(err){
            console.log(err);
            return;
        }
        res.json({
            mes:'注册成功',
            success:1,
            username:username

        })

    })
})



//下单接口
router.post('/order', function (req, res) {
    var order_id = new Date().getTime()+parseInt(Math.random()*100000);
    console.log(order_id);
    var product_id = req.body.product_id;
    var user_id = req.body.user_id;
    var price = req.body.price;
    var count = req.body.count;
    var all_price = req.body.all_price;
    var add_time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    var status = 1;
    var msg = "";
    var success = 0;
    async.parallel({
        user: function (callback) {
            DB.find("user", { _id: new DB.ObjectID(user_id) }, { username: 1, address: 1, tel: 1 }, {}, function (err, data) {
                callback(err, data)
            })
        },
        product: function (callback) {
            DB.find("product", { _id: new DB.ObjectID(product_id) }, { title: 1,img:1}, {}, function (err, data) {
                callback(err, data)
            })
        }
    }, function (err, data) {
        var product_title = data.product[0].title;
        var  product_img =  data.product[0].img;
        var username = data.user[0].username;
        var tel = data.user[0].tel;
        var address = data.user[0].address;
        DB.insertOne("order", { order_id: order_id, product_id: product_id,product_title: product_title,product_img:product_img,price: price,count: count,all_price: all_price,add_time: add_time,status: status,user_id: user_id,username: username,tel: tel,address: address }, function (err, data) {
            if (err) {
                console.log(err);
                msg="发生错误，下单失败";
                success = 0;
                return;
            }else{
                msg = "下单成功";
                success = 1;
            }
            res.json({
                msg:msg,
                success:success
            })
        })
    })
})
//订单列表接口
router.get('/orderContent', function(req, res) {
    var page=req.query.page || 1;
    var userid=req.query.userid;
    DB.find('order',{user_id:userid},{product_img:1,product_title:1,all_price:1,add_time:1},{pageSize:20,page:page},function(err,data){
        if(err){
            console.log(err);
            return;
        }
        res.json({
            result:data,
            success:true
        })
    })
});


//商品列表
router.get('/product', function(req, res) {
    var page=req.query.page;
     if(!page){
        page=1
     }
       DB.find('product',{},{title:1,img:1,price:1,old_price:1},{pageSize:10,page:page},function(err,data){
           if(err){
               console.log(err);
               return;
           }
           res.json({
               result:data,
               success:true
           })
       })
});
//商品详情
router.get('/productcontent', function(req, res) {
    var id=req.query.id;
    DB.find('product',{'_id':new ObjectID(id)},{},{},function(err,data){
        if(err){
            console.log(err);
            return;
        }
        res.json({
            result:data,
            success:true
        })
    })
});
//搜索商品
router.post('/searchproduct',function(req, res){
    var title = new RegExp(req.body.title,"")
    DB.find('product',{'title':title},{},{},function(err,data){
        if(err){
            console.log(err);
            return;
        }
        res.json({
            result:data,
            success:true
        })
    })
})

router.get('/article', function(req, res) {
      var page=req.query.page;
     if(!page){
        page=1
     }
       DB.find('article',{},{title:1,img:1},{pageSize:2,page:page},function(err,data){
           if(err){
               console.log(err);
               return;
           }
           res.json({
               result:data,
               success:true
           })
       })
});

router.get('/content', function(req, res) {
    var id=req.query.id;

    DB.find('article',{'_id':new ObjectID(id)},{title:1,content:1},{},function(err,data){
        if(err){
            console.log(err);
            return;
        }
        res.json({
            result:data,
            success:true
        })
    })
});

module.exports = router;
